package com.cgwx.controller;

import com.alibaba.fastjson.JSONObject;
import com.cgwx.Utils.result.ResultUtil;
import com.cgwx.aop.GetUserInfo;
import com.cgwx.config.BusinessException;
import com.cgwx.data.dto.UserInfo;
import com.cgwx.data.dto.UserRoomDto;
import com.cgwx.entity.*;
import com.cgwx.mapper.AuthorityMapper;
import com.cgwx.service.*;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@Api(tags = "共享空间")
//@ApiIgnore
@RequestMapping("/testCompany")
public class TestCompanyController {

    @Resource
    private IAuthorityService authorityService;

    @Resource
    private IFolderService folderService;

    @Resource
    private IFavoritesService favoritesService;

    @Resource
    private IRoomService roomService;

    @Resource
    private IUtilService utilService;

    @Resource
    private IUserRoomService userRoomService;

    @Resource
    private IPersonalRecycleBinService personalRecycleBinService;

    @Resource
    private AuthorityMapper authorityMapper;

    @GetMapping("/getUsedSpace")
    @GetUserInfo
    @ApiOperation("获取已占用空间大小（单位是MB")
    public Object getUsedSpace(@RequestBody UsUser user, String type) {
        String result = roomService.getUsedSpace(user.getAccount(), type);
        return ResultUtil.success(result);
    }

    @PostMapping("/checkAuthority")
    @ApiOperation("获取员工的单个文件（夹）权限")
    public Object checkAuthority(@RequestBody UsUser user, @RequestParam String entityId) {
        String authority = authorityService.checkAuthority(user.getAccount(), user.getDeptId(), entityId);
        if (authority.equals("0")) return ResultUtil.success("无权限!");
        else return ResultUtil.success(authority);
    }

    @PostMapping("/getMemberAuthority")
    @ApiOperation("获取成员及权限")
    public Object getMemberAuthority(@RequestBody UsUser user, @RequestParam String entityId) {
        List<AuthorityInfo> authorityInfos = authorityService.getMemberAuthority(user.getAccount(), user.getDeptId(), entityId);
        return ResultUtil.success(authorityInfos);
    }

    @PostMapping("/insertMember")
    @ApiOperation("添加成员")
    public Object insertMember(String account, String deptId, @RequestBody Map<String, Object> requestBody) {
        String entityId = (String) requestBody.get("entityId");
        List<Map<String, String>> depts = (List<Map<String, String>>) requestBody.get("proxyDept");
        List<Map<String, String>> ids = (List<Map<String, String>>) requestBody.get("proxyId");
        return ResultUtil.success(authorityService.insertMember(account, deptId, entityId, depts, ids));
    }

    @PostMapping("/updateMemberAuthority")
    @ApiOperation("修改成员权限")
    public Object updateMemberAuthority(String account, String deptId, @RequestParam String entityId, @RequestBody Map<String, Object> requestBody, @RequestParam String level) {
        List<Map<String, String>> depts = (List<Map<String, String>>) requestBody.get("proxyDept");
        List<Map<String, String>> ids = (List<Map<String, String>>) requestBody.get("proxyId");
        String result = authorityService.updateAuthority(account, deptId, entityId, depts, ids, level);
        return ResultUtil.success(result);
    }

    @PostMapping("/deleteAuthority")
    @ApiOperation("移除成员权限")
    public Object deleteAuthority(String account, String deptId, @RequestParam String entityId, @RequestParam String id, @RequestParam String type) {
        String result = authorityService.deleteAuthority(account, deptId, entityId, id, type);
        return ResultUtil.success(result);
    }

    @PostMapping("/uploadFile")
    @ApiOperation("上传文件")
    public Object uploadFile(@RequestParam String account, @RequestParam String name, @RequestParam String deptId, @RequestParam String parentId, @RequestParam MultipartFile multipartFile, @RequestParam String type) {
        Folder folder = new Folder();
        folder.setEntityId(parentId);
        String roomId = folderService.getFolder(folder).get(0).getEntityRoom();
        String result = utilService.uploadFile(account, name, deptId, roomId, parentId, type, multipartFile, "false");
        return ResultUtil.success(result);
    }

    @GetMapping("/getVersionFile")
    @ApiOperation("文件历史版本查询")
    public Object getVersionFile(@RequestParam String fileId) {
        List<MinioFileVersion> result = utilService.getVersionFile(fileId);
        return ResultUtil.success(result);
    }

    @GetMapping("/addTags")
    @ApiOperation("添加标签")
    public Object addTags(@RequestParam String entityId, @RequestParam String tags, @RequestParam String type) {
        List<String> tagList = JSONObject.parseArray(tags, String.class);
        String result = utilService.addTags("0064", "000306", entityId, tagList, type);
        return ResultUtil.success(result);
    }

    @GetMapping("/addFreeRoom")
    @ApiOperation("新建自由空间")
    public Object addFreeRoom(@RequestParam String account, @RequestParam String name, @RequestParam String roomName, @RequestParam String accounts) {
        List<String> accountList = JSONObject.parseArray(accounts, String.class);
        String result = roomService.insertFreeRoom(account, name, roomName, accountList);
        return ResultUtil.success(result);
    }

    @GetMapping("/freeRoomInsertStaff")
    @GetUserInfo
    @ApiOperation("自由空间添加员工")
    public Object freeRoomInsertStaff(@RequestParam String account, @RequestParam String deptId, @RequestParam String entityId, @RequestParam String accounts) {
        List<String> accountList = JSONObject.parseArray(accounts, String.class);
        String result = userRoomService.freeRoomInsertStaff(account, deptId, entityId, accountList);
        return ResultUtil.success(result);
    }

    @GetMapping("/freeRoomDeleteStaff")
    @GetUserInfo
    @ApiOperation("自由空间删除员工")
    public Object freeRoomDeleteStaff(@RequestParam String account, @RequestParam String deptId, @RequestParam String entityId, @RequestParam String accounts) {
        List<String> accountList = JSONObject.parseArray(accounts, String.class);
        String result = userRoomService.freeRoomDeleteStaff(account, deptId, entityId, accountList);
        return ResultUtil.success(result);
    }

    @GetMapping("/getMyFreeRoom")
    @ApiOperation("获取我的共享空间")
    @Transactional
    public Object getMyFreeRoom(@RequestParam String account) {
        Room room = new Room();
        room.setRoomId(account);
        room.setRoomType("free");
        List<Room> rooms = roomService.getRoom(room);
        return ResultUtil.success(rooms);
    }

    @GetMapping("/getFreeRoomInfo")
    @ApiOperation("获取某自由空间信息")
    @Transactional
    public Object getFreeRoomInfo(@RequestParam String id) {
        List<UserRoomDto> UserRoomDtos = userRoomService.getUserRoomById(id);
        return ResultUtil.success(UserRoomDtos);
    }

    @GetMapping("/deleteFreeRoomById")
    @ApiOperation("解散自由空间")
    @Transactional
    public Object deleteFreeRoomById(@RequestParam String account, @RequestParam String entityId, @RequestParam String id) {
        Room room = new Room();
        room.setId(id);
        room = roomService.getRoom(room).get(0);
        if(!account.equals(room.getRoomId())) throw new BusinessException("只有空间创建人可以解散空间!");
        if(!userRoomService.deleteUserRoomById(id)) throw new BusinessException("空间成员删除失败!");
        if(!roomService.deleteFreeRoom(id)) throw new BusinessException("空间删除失败!");
        List<String> fileFolders = authorityService.getChildrenAndMyself(entityId);
        Authority authority = new Authority();
        authority.setPermissionType("staff");
        for(String fileFolder : fileFolders) {
            authority.setEntityId(fileFolder);
            if(!authorityMapper.deleteAllAuthority(authority)) throw new BusinessException("空间权限删除失败!");
            if(!folderService.deleteFolderById(fileFolder).equals("删除成功!")) throw new BusinessException("文件夹删除失败!");
        }
        return ResultUtil.success("自由空间解散成功!");
    }

    @GetMapping("/downloadFile")
    @ApiOperation("下载单个文件")
    public Object downloadFile(@RequestParam String account, @RequestParam String deptId, @RequestParam String entityId, @RequestParam String type) {
        String Url = utilService.getURLByFileId(account, deptId, entityId, type);
        return ResultUtil.success(Url);
    }

    @PostMapping("/getTree")
    @ApiOperation("下载文件夹")
    public Object getTree(@RequestParam String userInfoJson, @RequestParam String fileFoldersJson, @RequestParam String zipName) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        UserInfo userInfo = objectMapper.readValue(userInfoJson, UserInfo.class);
        List<FileFolder> fileFolders = objectMapper.readValue(fileFoldersJson, new TypeReference<List<FileFolder>>(){});
        return ResultUtil.success();
    }

    @PostMapping("/viewFile")
    @ApiOperation("预览文件")
    public Object viewFile(@RequestParam String account, @RequestParam String deptId, @RequestParam String entityId, @RequestParam String type) {
        String result = utilService.viewFile(account, deptId, entityId, type);
        return ResultUtil.success(result);
    }

    @PostMapping("/rename")
    @ApiOperation("重命名文件(夹)")
    public Object rename(@RequestBody UsUser user, @RequestParam String entityName, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.rename(user.getAccount(), user.getDeptId(), entityName, entityId, parentId, type);
        return ResultUtil.success(result);
    }

    @PostMapping("/remove")
    @Transactional
    @ApiOperation("根据parentId移动个人文件（夹）")
    public Object remove(@RequestBody UsUser user, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.remove(user.getAccount(), user.getDeptId(), entityId, parentId, type);
        return ResultUtil.success(result);
    }

    @PostMapping("/insertFavorites")
    @ApiOperation("收藏")
    public Object insertFavorites(@RequestParam String[] entityIds) {
        String account = "0064";
        String result = favoritesService.insertFavorites(account, Arrays.asList(entityIds));
        return ResultUtil.success(result);
    }

    @PostMapping("/deleteFavorites")
    @ApiOperation("取消收藏")
    public Object deleteFavorites(@RequestParam String[] entityIds) {
        String account = "0064";
        String result = favoritesService.deleteFavorites(account, Arrays.asList(entityIds));
        return ResultUtil.success(result);
    }

    @PostMapping("/delete")
    @Transactional
    @ApiOperation("根据entityId删除文件（夹）")
    public Object delete(@RequestParam String[] entityIds) {
        String account = "0064";
        String deptId = "000306";
        String type = "dept";
        String result = utilService.delete(account, deptId, Arrays.asList(entityIds), type);
        return ResultUtil.success(result);
    }

    @PostMapping("/restore")
    @Transactional
    @ApiOperation("根据entityId恢复文件（夹）")
    public Object restore(@RequestParam String[] entityIds) {
        String account = "0064";
        String deptId = "000306";
        String type = "dept";
        String result = utilService.restore(account, deptId, Arrays.asList(entityIds), type);
        return ResultUtil.success(result);
    }

    @PostMapping("/removeRecycleBin")
    @Transactional
    @ApiOperation("从回收站移动到共享空间")
    public Object removeRecycleBin(@RequestBody UsUser user, @RequestParam String entityId, @RequestParam String parentId, @RequestParam String type) {
        String result = utilService.removeRecycleBin(user.getAccount(), user.getDeptId(), entityId, parentId, type);
        return ResultUtil.success(result);
    }
}